package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class DELEHandle implements Handle {
	FtpSession ftpSession;

	public DELEHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String fileName=line.substring(line.indexOf(" "));
		if(fileName==null||fileName.trim().length()<=0){
			os.write(("450 File unavailable.\r\n").getBytes());
			os.flush();
			return;
		}
		/**
		 * if not absolute path 
		 */
		if(!(fileName.charAt(0)=='/')){
			fileName=ftpSession.currentDir+"/"+fileName.trim();
		}
		String path = PathConvert.toServerPath(ftpSession.getRootDir(), fileName);
		File file = new File(path.trim());
		if(!file.exists()){
			os.write(("450 File unavailable.\r\n").getBytes());
			os.flush();
			return;
		}
		try{
			file.delete();
			os.write(("250 File deleted.\r\n").getBytes());
			os.flush();
		}catch(Exception e){
			os.write(("450 File unavailable.\r\n").getBytes());
			os.flush();
		}
		
	}
}

